<template>
  <div class="articalList">
    <van-pull-refresh :success-duration="1500" :success-text="refReshText" v-model="isPullLoading" @refresh="onRefresh">
       <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"

        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArticleItem  v-for="item in list" :key="item.art_id+''" :articleItem="item" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import { Toast } from 'vant'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      preTimestamp: this.preTimestamp || Date.now(),
      error: false,
      isPullLoading: false,
      refReshText: ''
    }
  },
  props: {
    channelsId: {
      type: Number,
      require: true
    }
  },
  created () {

  },
  components: {
    ArticleItem
  },
  methods: {
    async onLoad () {
      try {
        // 1. 发送请求获取数据
        const res = await getArticleList({
          channel_id: this.channelsId,
          timestamp: this.preTimestamp,
          with_top: 1
        })
        // if (Math.random() > 0.5) {
        //   console.lg(6)
        // }
        // 2.保存数据
        this.list.push(...res.results)
        this.preTimestamp = res.pre_timestamp
        // 3. 加载状态结束
        this.loading = false
        // 4. 数据全部加载完成
        if (!this.preTimestamp) {
          this.finished = true
        }
      } catch (error) {
        Toast.clear()
        this.loading = false
        this.error = true
      }
    },
    async  onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelsId,
          timestamp: Date.now(),
          with_top: 1
        })
        // if (Math.random() > 0.5) {
        //   console.lg(6)
        // }
        console.log(res)
        this.list.unshift(...res.results)
        this.isPullLoading = false
        this.refReshText = '亲,共刷新' + res.results.length + '条数据'
      } catch (error) {
        this.refReshText = '亲,加载失败,稍后重试'
        this.isPullLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .articalList{
    height: 80vh;
    overflow-y: scroll;

  }
</style>
